/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
* MyTabbedPane.java
*
* Created on November 14, 2007, 1:54 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
 */
package javautil.swing.tabbedPane;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;

/**
 *
 * @author stewari1
 */
public class MyTabbedPane extends JTabbedPane {

    /**
     * Constructs ...
     */
    public MyTabbedPane() {

        super(JTabbedPane.TOP);

        addMouseListener(new java.awt.event.MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                tabClicked(e);
            }

        });
    }

    /**
     * Method description
     *
     * @param e description
     */
    private void tabClicked(MouseEvent e) {

        if ((e.getButton() != MouseEvent.BUTTON1) && (e.getClickCount() == 1)) {    // if is right-click


            // create popup with Close menuitem
            JPopupMenu popupMenu = new JPopupMenu();
            JMenuItem closeBtn   = new JMenuItem("Close");

            closeBtn.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {

                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            closeSelectedTab();
                        }

                    });
                }

            });
            popupMenu.add(closeBtn);


            // display popup near location of mouse click
            popupMenu.show(e.getComponent(), e.getX(), e.getY() - 10);
        }
    }

    /**
     * Method description
     */
    private void closeSelectedTab() {


        // do cleanup
        remove(getSelectedIndex());    // remove selected tab
    }
}
